var zTree;
var demoIframe;
var ctx = '/BTFinder';

function addHoverDom(treeId, treeNode) {
	var sObj = $("#" + treeNode.tId + "_span");
	if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0)
		return;
	var addStr = "<span class='button remove' id='removeBtn_" + treeNode.tId
			+ "' title='add node' onfocus='this.blur();'></span>";

	addStr += "<span class='button add' id='addBtn_" + treeNode.tId
			+ "'></span>";
	addStr += "<span class='button edit' id='editBtn_" + treeNode.tId
			+ "'></span>";
	sObj.after(addStr);
	var btn = $("#addBtn_" + treeNode.tId);
	if (btn)
		btn.bind("click", function() {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.addNodes(treeNode, {
				id : (1000 + newCount),
				pId : treeNode.id,
				name : "new node" + (newCount++)
			});
			return false;
		});
};

function removeHoverDom(treeId, treeNode) {
	$("#addBtn_" + treeNode.tId).unbind().remove();
	$("#removeBtn_" + treeNode.tId).unbind().remove();
	$("#editBtn_" + treeNode.tId).unbind().remove();
};

var setting = {
//	check : {
//		enable : true
//	},
	view : {
	//	addHoverDom : addHoverDom,
		removeHoverDom : removeHoverDom,
		dblClickExpand : false,
		showLine : true,
		selectedMulti : false
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "pId",
			rootPId : ""
		}
	},
	callback : {
		onRename: zTreeOnRename,
		beforeRename:beforeRename,
		beforeRemove: zTreeBeforeRemove,
		onRemove: zTreeOnRemove,
		beforeClick : function(treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("tree");
			var id = treeNode.id;
			checkList(id);
		}, 
		beforeDblClick: function(treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("tree");
			if (treeNode.isParent) {
				zTree.expandNode(treeNode);
				return false;
			}
		},
		onRightClick: function(event,treeId, treeNode){
			if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
				zTree.cancelSelectedNode();
				showRMenu("root", event.clientX, event.clientY);
			} else if (treeNode && !treeNode.noR) {
				zTree.selectNode(treeNode);
				showRMenu("node", event.clientX, event.clientY);
			}
		},
	}
};

/**
 * 配置文件（如果没有默认字样，说明默认值就是注释下的值）
 * 但是，on*（onSelect， onMaxSizeExceed...）等函数的默认行为
 * 是在ID为i_stream_message_container的页面元素中写日志
 */
	var config = {
		browseFileId : "i_select_files", /** 选择文件的ID, 默认: i_select_files */
		browseFileBtn : "<div>请选择文件</div>", /** 显示选择文件的样式, 默认: `<div>请选择文件</div>` */
		dragAndDropArea: "i_select_files", /** 拖拽上传区域，Id（字符类型"i_select_files"）或者DOM对象, 默认: `i_select_files` */
		dragAndDropTips: "<span>把文件(文件夹)拖拽到这里</span>", /** 拖拽提示, 默认: `<span>把文件(文件夹)拖拽到这里</span>` */
		filesQueueId : "i_stream_files_queue", /** 文件上传容器的ID, 默认: i_stream_files_queue */
		filesQueueHeight : 200, /** 文件上传容器的高度（px）, 默认: 450 */
// 		messagerId : "i_stream_message_container", /** 消息显示容器的ID, 默认: i_stream_message_container */
		multipleFiles: true, /** 多个文件一起上传, 默认: false */
		onRepeatedFile: function(f) {
			alert("文件："+f.name +" 大小："+f.size + " 已存在于上传队列中。");
			return false;	
		},
//		autoUploading: false, /** 选择文件后是否自动上传, 默认: true */
//		autoRemoveCompleted : true, /** 是否自动删除容器中已上传完毕的文件, 默认: false */
//		maxSize: 104857600//, /** 单个文件的最大大小，默认:2G */
//		retryCount : 5, /** HTML5上传失败的重试次数 */
//		postVarsPerFile : { /** 上传文件时传入的参数，默认: {} */
//			param1: "val1",
//			param2: "val2"
//		},
//		swfURL : "/swf/FlashUploader.swf", /** SWF文件的位置 */
		tokenURL : ctx + "/tk", /** 根据文件名、大小等信息获取Token的URI（用于生成断点续传、跨域的令牌） */
		frmUploadURL : ctx + "/fd;", /** Flash上传的URI */
		uploadURL : ctx + "/upload", /** HTML5上传的URI */
//		simLimit: 200, /** 单次最大上传文件个数 */
//		extFilters: [".txt", ".rpm", ".rmvb", ".gz", ".rar", ".zip", ".avi", ".mkv", ".mp3"], /** 允许的文件扩展名, 默认: [] */
//		onSelect: function(list) {alert('onSelect')}, /** 选择文件后的响应事件 */
//		onMaxSizeExceed: function(size, limited, name) {alert('onMaxSizeExceed')}, /** 文件大小超出的响应事件 */
//		onFileCountExceed: function(selected, limit) {alert('onFileCountExceed')}, /** 文件数量超出的响应事件 */
//		onExtNameMismatch: function(name, filters) {alert('onExtNameMismatch')}, /** 文件的扩展名不匹配的响应事件 */
//		onCancel : function(file) {alert('Canceled:  ' + file.name)}, /** 取消上传文件的响应事件 */
//		onComplete: function(file) {alert('onComplete')}, /** 单个文件上传完毕的响应事件 */
//		onQueueComplete: function() {alert('onQueueComplete')}, /** 所以文件上传完毕的响应事件 */
//		onUploadError: function(status, msg) {alert('onUploadError')} /** 文件上传出错的响应事件 */
//		onDestroy: function() {alert('onDestroy')} /** 文件上传出错的响应事件 */
	};
	


$(document).ready(function() {
var _t = new Stream(config);
	pageInit();
var page = {
//	init: function() {
//		$.ajax({
//			url:'btfinder.java', 
//			data: {command: 'init', hash: Math.random()},
//			success: function(e) {
//				 console.log(e);
//				 var zNodes = e;
//				 var t = $("#tree");
//				 t = $.fn.zTree.init(t, setting, zNodes);
//				 demoIframe = $("#testIframe");
//				 demoIframe.bind("load", loadReady);
//				 zTree = $.fn.zTree.getZTreeObj("tree");
//				 rMenu = $("#rMenu");
//				 var nodes = zTree.getNodes();
//				 console.log(nodes);
//
////			zTree.selectNode(zTree.getNodeByParam("id", 101));
//			}
//		});
//	},
	uploadFiles: function() {
		var formData = new FormData($( "#uploadForm" )[0]);  
	     $.ajax({  
	          url: 'btfinder.java' ,  
	          type: 'POST',  
	          data: formData,  
	          async: false,  
	          cache: false,  
	          mimeType: "multipart/form-data",
	          contentType: false,  
	          processData: false,  
	          success: function (returndata) {  
	              alert(returndata);  
	          },  
	          error: function (returndata) {  
	              alert(returndata);  
	          }  
	     });  
	}
};

//init page 
//page.init();

//
$('#upload').click(function() {
	$('#uploadform').show();
	$('#fileInput').click();
});
//
$('#bt-upload').click(function() {
	page.uploadFiles();
	return false;
});

});
function pageInit(){
	$.ajax({
		url:'btfinder.java', 
		data: {command: 'init', hash: Math.random()},
		success: function(e) {
			 var zNodes = e;
			 var t = $("#tree");
			 t = $.fn.zTree.init(t, setting, zNodes);
			 demoIframe = $("#testIframe");
			 demoIframe.bind("load", loadReady);
			 zTree = $.fn.zTree.getZTreeObj("tree");
			 rMenu = $("#rMenu");
			 var nodes = zTree.getNodes();

//		zTree.selectNode(zTree.getNodeByParam("id", 101));
		}
	});
}
function loadReady() {
	var bodyH = demoIframe.contents().find("body").get(0).scrollHeight, htmlH = demoIframe
			.contents().find("html").get(0).scrollHeight, maxH = Math.max(
			bodyH, htmlH), minH = Math.min(bodyH, htmlH), h = demoIframe
			.height() >= maxH ? minH : maxH;
	if (h < 530)
		h = 530;
	demoIframe.height(h);
}

function checkList(id){
	var ids = encodeURI(id);
	$.ajax({
		url:'btfinder.java',
		data: {command:"getFiles",id:ids, hash: Math.random()},
		success: function(e) {
			 console.log(e);

			$("#list").html()
		}
	});
}
function showRMenu(type, x, y) {
	$("#rMenu ul").show();
	if (type=="root") {
		$("#m_del").hide();
		$("#m_update").hide();
		$("#m_add").hide();
	} else {
		$("#m_del").show();
		$("#m_update").show();
		$("#m_add").show();
	}

    y += document.body.scrollTop;
    x += document.body.scrollLeft;
    rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

	$("body").bind("mousedown", onBodyMouseDown);
}
function hideRMenu() {
	if (rMenu) rMenu.css({"visibility": "hidden"});
	$("body").unbind("mousedown", onBodyMouseDown);
}
function onBodyMouseDown(event){
	if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
		rMenu.css({"visibility" : "hidden"});
	}
}
//显示新增
function showRMenu2(x, y) {  
    $("#rMenu2").show();  
    $("#rMenu2").css({ "top": y + "px", "left": x + "px", "visibility": "visible" });  
    $("body").bind("mousedown", onBodyMouseDown);  
}  

var addCount = 1;
function addTreeNode() {
	hideRMenu();
//	var tag = 0;
//	$("#tree").mousemove(function (e) {  
//        if (tag == 0) showRMenu2(e.pageX, e.pageY);  
//        $("#caption_bbs").focus();  
//        tag = tag + 1;  
//    });  
	var treeObj = $.fn.zTree.getZTreeObj("tree");
		nodes = treeObj.getSelectedNodes();
		treeNode  = nodes[0];
	if (nodes) {
		treeNode = zTree.addNodes(treeNode, {id:(100 + addCount),type:"1",pId:treeNode.id, isParent:false, name:"新建文件夹" + (addCount++)});
		console.log(treeNode);
	} else {
		zTree.addNodes(null, newNode);
	}
	if (treeNode) {
		zTree.editName(treeNode[0]);
	} else {
		alert("叶子节点被锁定，无法增加子节点");
	}

}

//function addTree(){
//	   var zTree = $.fn.zTree.getZTreeObj("tree");  
//       var nodes = zTree.getSelectedNodes();  
//		 alert(nodes[0].id);
//       var id = nodes[0].id+"\\"+$("#caption_bbs").val();
//   	$.ajax({
//   		url:'addFinder.java',
//   		data: {command: 'getFiles',pid:encodeURI(nodes[0].pId),id:encodeURI(id),name:$("#caption_bbs").val(), hash: Math.random()},
//   		success: function(e) {
//			 console.log(e);
//   		 var treeObj = $.fn.zTree.getZTreeObj("tree");  
//         var nodes = treeObj.getSelectedNodes();  
//         treeObj.reAsyncChildNodes(null, "refresh", true);  
//         if (e == 0) alert("操作失败！");  
//     }
//    });
//    $("#rMenu2").css({ "visibility": "hidden" });  
//    $("#caption_bbs").val("");  
//   		}
function removeTreeNode() {
	hideRMenu();
	var nodes = zTree.getSelectedNodes();
	
			zTree.removeNode(nodes[0],true);
		
}
function updateTreeNode() {
	hideRMenu();
	var zTree = $.fn.zTree.getZTreeObj("tree"),
	nodes = zTree.getSelectedNodes(),
	treeNode = nodes[0];
	if (nodes.length == 0) {
		alert("请先选择一个节点");
		return;
	}
	
	zTree.editName(treeNode);

}
function beforeRename(treeId, treeNode, newName) {
	if (newName.length == 0) {
		alert("节点名称不能为空.");
		var zTree = $.fn.zTree.getZTreeObj("tree");
		setTimeout(function(){zTree.editName(treeNode)}, 10);
		return false;
	}
	if(treeNode.type != 1){
	treeNode.type = treeNode.id;
}
	return true;
}

function zTreeOnRename(event, treeId, treeNode, isCancel) {
	//type设置为1为增加文件夹
	if(treeNode.type == 1){
		alert(treeId);
	var id = treeNode.pId+"\\"+treeNode.name;
	$.ajax({
		url:'addFinder.java',
		data: {command: 'getFiles',pid:encodeURI(treeNode.pId),id:encodeURI(id),name:treeNode.name, hash: Math.random()},
		success: function(e) {
			if(e.erro == 0){
				alert("不能创建根目录");
			}
			if(e.success == true){
				pageInit();
				
				}
			 console.log(e);
		}
	});
	} else {
		//修改文件名
		var id = treeNode.pId+"\\"+treeNode.name;
		$.ajax({
			url:'upFinder.java',
			data: {command: 'getFiles',type:encodeURI(treeNode.type),pid:encodeURI(treeNode.pId),id:encodeURI(id),name:treeNode.name, hash: Math.random()},
			success: function(e) {
				 console.log(e);
			}
	  });
   }
}
function zTreeBeforeRemove(treeId, treeNode) {
	if(treeNode.pId == null || treeNode.pId.length == 0){
		return false;
	}
	var msg = "要删除的目录会连同目录下的文件一起删掉。\n\n请确认！";
	if (confirm(msg)==true){
		return true;
	} else {
		return false;
	}
}
function zTreeOnRemove(event, treeId, treeNode) {
	var id = treeNode.pId+"\\"+treeNode.name;
		$.ajax({
		url:'delFinder.java',
		data: {command: 'getFiles',pid:encodeURI(treeNode.pId),id:encodeURI(id), hash: Math.random()},
		success: function(e) {
			 console.log(e);
		}
	});
	
}